package com.design.marketPrj.application.controller.alipay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.base.oauth.models.AlipaySystemOauthTokenResponse;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.alipay.easysdk.util.generic.models.AlipayOpenApiGenericResponse;
import com.design.marketPrj.application.controller.BaseController;
import com.design.marketPrj.application.service.PayService;
import com.design.marketPrj.application.util.UUIDUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.UUID;

@Controller
public class AlipayController extends BaseController {

    @Autowired
    PayService payService;

    //发起支付操作
    @RequestMapping("/testPay")
    public void createWebTrade(HttpServletResponse response,String moneyToPay){
        String returnUrl = "http://127.0.0.1:8080/paySuccessUrl";
        // 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions());
        try {
            //在数据库中插入一条数据以记录本次充值数据
            String payNo = payService.payHistoryCreate(getUser(),new BigDecimal(moneyToPay));
            // 发起API调用（以创建当面付收款二维码为例）
            AlipayTradePagePayResponse alipayResponse = payService.createWebTradeForm("账户充值", payNo, moneyToPay,returnUrl);
            // 处理响应或异常
                System.out.println("支付成功");
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write(alipayResponse.getBody());// 直接将完整的表单html输出到页面
                response.getWriter().flush();
                response.getWriter().close();
        } catch (Exception e) {
            System.err.println("支付失败，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    //取现操作
    @RequestMapping("/testTransfer")
    @ResponseBody
    public JSONObject createWebTransfer(String moneyToTransfer){
        //设置全局参数
        Factory.setOptions(getOptions());
        String identity;

        JSONObject returnObject = new JSONObject();
        if(getAliBind()){
            try {
                identity = payService.getAuthCode(getUserId());
            }
            catch (Exception e){
                e.printStackTrace();
                returnObject.put("code",500);
                returnObject.put("msg","未获取到已绑定对应的支付宝账户!");
                return returnObject;
            }
        }
        else {
            returnObject.put("code",500);
            returnObject.put("msg","该账号尚未绑定支付宝账号!");
            return returnObject;
        }
        try {
            //在数据库中插入一条数据以记录本次取款数据
            String transferNo = payService.transferHistoryCreate(getUser(),new BigDecimal(moneyToTransfer));
            if(transferNo == null){
                returnObject.put("code",500);
                returnObject.put("msg","余额不足!");
                return returnObject;
            }
            //创建线程异步调用支付宝api
            new Thread(() -> {
                try {
                    AlipayOpenApiGenericResponse alipayOpenApiGenericResponse = payService.createTransferForm(moneyToTransfer,transferNo,identity);
                    System.out.println("取现成功");
                    payService.transferSuccess(transferNo,new BigDecimal(moneyToTransfer));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
            returnObject.put("code",200);
            returnObject.put("msg","取款申请已提交，您稍后能收到资金。");
            return returnObject;
        } catch (Exception e) {
            System.err.println("取现失败，原因：" + e.getMessage());
            returnObject.put("code",500);
            returnObject.put("msg","取现失败!");
            return returnObject;
        }
    }

    //支付成功回调页
    @RequestMapping(value = "/paySuccessUrl",method = RequestMethod.GET)
    public Object paySuccessUrl(HttpServletRequest request, Model model){
        String tradeNo = request.getParameter("out_trade_no");
        BigDecimal moneyToAdd = new BigDecimal(request.getParameter("total_amount"));
        payService.paySuccess(tradeNo,moneyToAdd);
        System.out.println(request.getParameterMap());
        model.addAttribute("user",getUser());
        return "user/userPaySuccess";
    }

    @RequestMapping("/alipayAuth")
    public String alipayAuth(HttpSession session,HttpServletResponse response){
        String uuid = UUIDUtils.getUUID();
        session.setAttribute("state", uuid);
        String url = payService.userAuth(uuid,getOptions().appId);
        return "redirect:"+url;
    }

    @RequestMapping("/alipayAuthReturn")
    public String alipayAuthReturn(HttpServletRequest request){
        //设置全局参数
        Factory.setOptions(getOptions());
        // 获取session
        HttpSession session = request.getSession();
        // 得到auth_code
        String authCode = request.getParameter("auth_code");
        // 我们放在地址中的状态码
        String state = request.getParameter("state");
        String uuid = (String) session.getAttribute("state");
        // 验证信息我们发送的状态码
        if (null != uuid) {
            // 状态码不正确，直接返回登录页面
            if (!uuid.equals(state)) {
                return "redirect:/logout";
            }
        }
        //获取账户具体信息
        try{
            AlipaySystemOauthTokenResponse alipaySystemOauthTokenResponse = payService.getToken(authCode);
            String appAuthId = alipaySystemOauthTokenResponse.getUserId();
            payService.userAuthSuccess(appAuthId,getUserId());
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:/userTransfer";
    }


    private static Config getOptions() {
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = "openapi.alipaydev.com";
        config.signType = "RSA2";
        config.appId = "2021000117648654";
        config.merchantPrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC2W3ARUbBelemBhU2iOP/yq5HChytgvgEbH1DnRbVS66+a0AMovNcxW1sgjqVgm9iG83/cTA/UVlVFA6IVNAWuPEssbkhKL6/rDZPZDAVhdsmrggKTH6JNtlkpQUfQULKDuyD8I7LyoXMgTlxK7iB+UywZbd4iox0L5Ndff0IEuH16Vy9XkPiTt9U4JDZqYKOW2ief0xxL0eeTv6xxYZiXXw7NZWRJXeWIRAk/1Xyj9r+Nwp6PolUvG55LFpZQXHZRBBgvTbXisGJj+Y31q8Z0RUl+/oYO1GLWRRl3KIa5LEaw29WdP3TSfmauD0erG/jqzuebXrQ/u0c7dOJg8uqjAgMBAAECggEAMpr/Z57+zdDWYx4mJC2jQanBInW2YPt5fRhcsEGVBzTmn5S4O7bkFQtgJ5HObRfyp8itI+prviZTNXrDoRS1utt6lRLptsSzEgzLicEfQSPg5VqH8mIl/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